package edu.cmu.vlis.datamining.utils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Set;

import java.util.Iterator;

import org.jgrapht.graph.Multigraph;

import edu.cmu.vlis.datamining.core.Edge;
import edu.cmu.vlis.datamining.core.Vertex;

public class IOUtils {


    //Method which requires a file object

    public Object deserialzeObjFrom(File binGraphFile) {
        try {
            return new ObjectInputStream(new FileInputStream(binGraphFile)).readObject();

        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        throw new RuntimeException("Problem in deserialzing graph.");

    }

    /*public void buildGraph() {
		try {
			FileReader fstream = new FileReader("testGraph");
			BufferedReader i = new BufferedReader(fstream);
			String line;

			wg  = new DefaultDirectedWeightedGraph<Vertex,Edge>(new ClassBasedEdgeFactory<Vertex,Edge>(Edge.class)); ;
			vertexMap = new HashMap<String, Vertex>();
			while(( line = i.readLine() )!=null) {
				  String[] str = line.split(" ");
				  Vertex v1;
				  if(this.vertexMap.containsKey(str[0])) {
					  v1 = this.vertexMap.get(str[0]);
				  }
				  else {
					  v1 = new Vertex(Integer.parseInt(str[0]));
					  this.vertexMap.put(str[0], v1);
					  wg.addVertex(v1);
				  }

                   Vertex v2;
				  if(this.vertexMap.containsKey(str[2])) {
					  v2 = this.vertexMap.get(str[2]);
				  }
				  else {
					  v2 = new Vertex(Integer.parseInt(str[2]));
					  this.vertexMap.put(str[0], v2);
					  wg.addVertex(v2);
				  }

				  Vertex v3;
				  if(this.vertexMap.containsKey(str[3])) {
					  v3 = this.vertexMap.get(str[3]);
				  }
				  else {
					  v3 = new Vertex(Integer.parseInt(str[3]));
					  this.vertexMap.put(str[0], v3);
					  wg.addVertex(v3);
				  }

				  wg.addEdge(v1, v2);
				  wg.addEdge(v1, v3);
			}


			i.close();

			System.out.println("serializing the Graph");
			try {
				ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("LinkPrediction/theGrpah.dat"));
				oos.writeObject(wg);
				oos.close();
			}
			catch (Exception e) { e.printStackTrace(); 
			}


		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println("Graph cannot be saved as File cannot be opened");
			return;
		}	


	}
     */

    public void serailizeObj(final Object obj, File graphFile ) {
        System.out.println("serializing the obj to: "+graphFile.getAbsolutePath());
        try {
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(graphFile));
            oos.writeObject(obj);
            oos.flush();
            oos.close();

        }
        catch (IOException e) { e.printStackTrace(); 
        }

    }       


    public void persistGraphAsText(Multigraph<Vertex,Edge > wg, File textFile) {
        //open the file
        try {
            BufferedWriter out = new BufferedWriter(new FileWriter(textFile));

            //Write a text file
            Iterator<Vertex> it = wg.vertexSet().iterator();
            while (it.hasNext()) {
                Vertex v = it.next();
                String line = Integer.toString(v.getVertexId()) + " " + v.getVertexUrl() +" : ";
                Set<Edge> edgeSet =  wg.outgoingEdgesOf(v);
                Iterator<Edge> it1 =edgeSet.iterator();
                boolean flagHasEdge =false;
                while(it1.hasNext()) {
                    Edge edge = it1.next();
                    Vertex target =  edge.getTarget();
                    line = line + Integer.toString(target.getVertexId()) + " ";
                    if(!flagHasEdge)
                        flagHasEdge = true;
                }
                if(flagHasEdge) {
                    out.write(line);
                    System.out.println(line);
                    out.write("\n");
                }
            }
            out.close();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            System.out.println("Graph cannot be saved as File cannot be opened");
            return;
        }	
    }

}
